<template>
  <div class="dialog">
    <el-dialog
      :title="'基础告警'+titleText"
      :visible.sync="showDialog"
      width="55%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        class="el-form"
        :rules="rules"
      >
        <el-form-item label="模板选择：" class="w50p">
          <el-select
            v-model="nowalarmTemplateId"
            clearable
            filterable
            @change="changeTemplate"
          >
            <el-option
              v-for="(item,index) in alarmTemplateList"
              :key="index"
              :value="item.alarmTemplateId"
              :label="item.templateName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备选择：" class="w50p" prop="equipmentCode">
          <el-select
            v-model="formData.equipmentNo"
            filterable
            clearable
            placeholder="请选择设备名称"
            @change="equipChange"
          >
            <el-option
              v-for="item of equipmentArr"
              :key="item.equipmentCode"
              :label="item.equipmentName"
              :value="item.equipmentCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="告警名称：" class="w50p" prop="baseAlarmName">
          <el-input v-model="formData.baseAlarmName" placeholder="请输入告警名称" />
        </el-form-item>
        <el-form-item label="监测数据项：" class="w50p" prop="dataItemId">
          <el-select
            v-model="nowdataitemindex"
            filterable
            clearable
            :placeholder="formData.dataItemName"
            @change="chandataitem"
          >
            <el-option
              v-for="(item,index) in dataItemList"
              :key="index"
              :value="index"
              :label="item.originalName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发送间隔:" class="w50p" prop="sendingInterval">
          <el-input v-model="formData.sendingInterval" disabled clearable />
        </el-form-item>
        <el-form-item label="滤波值：" class="w50p" prop="filteringValue">
          <el-input
            v-model="formData.filteringValue"
            clearable
            placeholder="请输入滤波值"
          />
        </el-form-item>
        <el-form-item label="滤波类型：" class="w50p" prop="filteringType">
          <el-select
            v-model="formData.filteringType"
            clearable
            filterable
            placeholder="请选择滤波类型"
          >
            <el-option
              v-for="(item,index) in filteringTypeList"
              :key="index"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="告警通知配置:" class="w50p">
          <el-select v-model="formData.noticeConfigNo" clearable filterable>
            <el-option
              v-for="(item,index) in contactTemplateArr"
              :key="index"
              :value="item.noticeConfigNo"
              :label="item.noticeConfigName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上限列表:" class="w50p">
          <div>
            <div class="line">
              <el-input
                v-model="basetopList.levelName"
                clearable
                placeholder="级别名称"
              />
              <el-input
                v-model="basetopList.thresholdValue"
                clearable
                placeholder="级别阈值"
              />
              <el-select v-model="basetopList.alarmTypeId">
                <el-option
                  v-for="(item,index) in alarmTypeList"
                  :key="index"
                  :label="item.alarmTypeName"
                  :value="item.alarmTypeId"
                />
              </el-select>
              <div class="line-click" @click="addtopList()">
                <i class="el-icon-plus"></i>
              </div>
            </div>
            <div v-for="(item,index) in nowtopList" :key="index" class="line">
              <el-input
                v-model="nowtopList[index].levelName"
                clearable
                placeholder="级别名称"
              />
              <el-input
                v-model="nowtopList[index].thresholdValue"
                clearable
                placeholder="级别阈值"
              />
              <el-select v-model="nowtopList[index].alarmTypeId">
                <el-option
                  v-for="(alarmTypeitem,alarmTypeindex) in alarmTypeList"
                  :key="alarmTypeindex"
                  :label="alarmTypeitem.alarmTypeName"
                  :value="alarmTypeitem.alarmTypeId"
                />
              </el-select>
              <div class="line-click" @click="deltopList(index)">
                <i class="el-icon-minus"></i>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="下限列表:" class="w50p">
          <div>
            <div class="line">
              <el-input
                v-model="basebottomList.levelName"
                clearable
                placeholder="级别名称"
              />
              <el-input
                v-model="basebottomList.thresholdValue"
                clearable
                placeholder="级别阈值"
              />
              <el-select v-model="basebottomList.alarmTypeId">
                <el-option
                  v-for="(item,index) in alarmTypeList"
                  :key="index"
                  :label="item.alarmTypeName"
                  :value="item.alarmTypeId"
                />
              </el-select>
              <div class="line-click" @click="addbottomList()">
                <i class="el-icon-plus"></i>
              </div>
            </div>
            <div
              v-for="(item,index) in nowbottomList"
              :key="index"
              class="line"
            >
              <el-input
                v-model="nowbottomList[index].levelName"
                clearable
                placeholder="级别名称"
              />
              <el-input
                v-model="nowbottomList[index].thresholdValue"
                clearable
                placeholder="级别阈值"
              />
              <el-select v-model="nowbottomList[index].alarmTypeId">
                <el-option
                  v-for="(alarmTypeitem,alarmTypeindex) in alarmTypeList"
                  :key="alarmTypeindex"
                  :label="alarmTypeitem.alarmTypeName"
                  :value="alarmTypeitem.alarmTypeId"
                />
              </el-select>
              <div class="line-click" @click="delbottomList(index)">
                <i class="el-icon-minus"></i>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import basicAlarmConfigurationApi from "@/api/monitoring-alarm/basic-alarm-configuration";
// import alarmTemplateConfigurationApi from "@/api/monitoring-alarm/alarm-template-configuration";
import equipScrapRecordApi from "@/api/equip-manage/equip-scrap-record";
import contactnot from "@/api/monitoring-alarm/system-notification-configuration/index";
import equipConfigDataItemApi from "@/api/basic-info-manage/equip-config-dataitem";
// import alarmCategoryManagementApi from "@/api/monitoring-alarm/alarm-category-management";
// import historicalAlarmRecordApi from "@/api/monitoring-alarm/historical-alarm-record/index";

export default {
  name: "",
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: "",
    },
    nowChanceStau: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      },
    },
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value % 1 === 0) {
          callback();
        } else {
          return callback(new Error("请输入整数！"));
        }
      }
    };
    return {
      formData: {},
      rules: {
        thresholdAlarmName: [
          {
            required: true,
            message: "请输入告警名称",
            trigger: ["change", "blur"],
          },
        ],
        // dataItemId: [
        //   { required: true, message: "请选择监测数据项", trigger: ["change", "blur"] }
        // ],
        equipmentNo: [
          {
            required: true,
            message: "请选择设备选择",
            trigger: ["change", "blur"],
          },
        ],
        // sendingInterval: [
        //   { required: true, message: "请输入发送间隔", trigger: ["change", "blur"] }
        // ],
        filteringValue: [
          {
            required: true,
            message: "请输入滤波值",
            trigger: ["change", "blur"],
          },
          { validator: checkInt, trigger: ["change", "blur"] },
        ],
        filteringType: [
          {
            required: true,
            message: "请输入滤波类型",
            trigger: ["change", "blur"],
          },
        ],
      },
      // 主要联系人
      alarmContactId: "",
      showDialog: this.show,
      // 数值告警时
      dataItemList: [],
      // 监测数据项
      nowdataitemindex: "",
      // 告警模板
      nowalarmTemplateId: "",
      alarmTemplateList: [],
      // 查询未入账的设备
      equipmentArr: [],
      // 联系人可选择列表
      contactTemplateArr: [],
      // 上限列表
      basetopList: {
        levelName: "",
        alarmTypeId: "",
        thresholdType: "max",
        thresholdValue: "",
      },
      nowtopList: [],
      // 下限列表
      basebottomList: {
        alarmTypeId: "",
        levelName: "",
        thresholdType: "min",
        thresholdValue: "",
      },
      nowbottomList: [],
      // 滤波类型
      nowfilterType: {},
      filteringTypeList: [
        {
          name: "时间",
          id: "TIME",
        },
        {
          name: "次数",
          id: "NUMBER",
        },
      ],
      // 告警类型下拉数据
      alarmTypeList: [],
      dataItemAllList: [],
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      if (v === "add") {
        this.formData = {};
        this.basetopList = {
            alarmLimitName: "",
            alarmLimitType: 0,
            alarmLimitValue: "",
          }
        // 下限列表
        this.basebottomList =  {
            alarmLimitName: "",
            alarmLimitType: 1,
            alarmLimitValue: "",
          }
      }
      if (v === "edit") {
        this.formData = this.editObject;
        this.basetopList = {};
        this.basebottomList = {};
        this.changeDataItem(this.formData.dataItemId);
        this.queryAlarm(this.formData.thresholdAlarmCode);
      }
      console.log("nowChanceStau", this.formData);
    },
  },
  created() {
    this.queryDataItemList();
    this.queryEquipment();
    this.queryByCondition();
    this.getalarmTemplatelist();
  },
  mounted() {},
  methods: {
    // 选择模板
    changeTemplate(e) {
      basicAlarmConfigurationApi.getalarmTemplatemessagelist(e).then((res) => {
        let row = res.data;
        if (this.nowalarmTemplateId > 0) {
          this.chancetemplelist(row);
        }
      });
    },
    // 选择模板时的数据处理
    chancetemplelist(zhrow) {
      this.formData = {};
      let row = JSON.parse(JSON.stringify(zhrow));
      if (row.alarmTemplateId) {
        this.formData = {
          alarmTemplateId: row.alarmTemplateId,
          templateName: row.templateName,
          sendingInterval: row.sendingInterval,
          filterValue: row.filterValue,
          filterType: row.filterType,
          noticeConfigNo: row.noticeConfigNo,
          // dataTypeId: row.dataTypeId,
          // dataTypeName: row.dataTypeName
        };
        basicAlarmConfigurationApi
          .getalarmTypelist(row.dataTypeId)
          .then((res) => {
            let data = res.data;
            this.chancealarmtype(data);
          });
        let mainlist = row.alarmTemplateThresholdList;
        console.log(mainlist);
        // 上限列表和下限列表的赋值
        this.basetopList = {
          levelName: "",
          alarmTypeId: "",
          thresholdType: "max",
          thresholdValue: "",
        };
        this.nowtopList = [];
        this.basebottomList = {
          levelName: "",
          alarmTypeId: "",
          thresholdType: "min",
          thresholdValue: "",
        };
        this.nowbottomList = [];
        for (var i = 0; i < mainlist.length; i++) {
          if (mainlist[i].thresholdType === "max") {
            if (this.basetopList.levelName.length === 0) {
              this.basetopList = mainlist[i];
            } else {
              this.nowtopList.push(mainlist[i]);
            }
          } else if (mainlist[i].thresholdType === "min") {
            if (this.basebottomList.levelName.length === 0) {
              this.basebottomList = mainlist[i];
            } else {
              this.nowbottomList.push(mainlist[i]);
            }
          }
        }
      }
    },
    // 处理数据类型数据
    chancealarmtype(list) {
      let newlist = [];
      list.forEach((item, index) => {
        newlist.push(item.alarmType);
      });
      this.alarmTypeList = newlist;
    },
    // 查询告警联系人
    queryByCondition() {
      contactnot
        .querybycondition({ organizationNo: sessionStorage.organizationNo })
        .then((res) => {
          if (res.code === 1) {
            let data = res.data || [];
            this.contactTemplateArr = data;
          }
        });
    },
    // 查看已配置告警详情
    queryAlarm(thresholdAlarmCode) {
      basicAlarmConfigurationApi.query(thresholdAlarmCode).then((res) => {
        if (res.code === 1) {
          let data = res.data.alarmLimitList || [];
          // 上限列表和下限列表的赋值
          data.forEach((a) => {
            if (a.alarmLimitType === "SUPERIOR_LIMIT") {
              a.alarmLimitType === 0;
              this.basetopList = {...a};
            }
            if (a.alarmLimitType === "LOWER_LIMIT") {
              a.alarmLimitType === 1;
              this.basebottomList = { ...a};
            }
          });
        }
      });
    },
    // 查询可选模版
    getalarmTemplatelist() {
      basicAlarmConfigurationApi.getalarmTemplatelist().then((res) => {
        this.alarmTemplateList = res.data;
      });
    },
    // 查询数据项项
    queryDataItemList() {
      // 获取所有监测数据项
      basicAlarmConfigurationApi.getdataitemlist().then((res) => {
        if (res.code === 1) {
          this.dataItemList = res.data || [];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 条件查询设备
    queryEquipment() {
      this.equipmentArr = [];
      equipScrapRecordApi.queryEquipment({}).then((res) => {
        if (res.code === 1) {
          let data = res.data || [];
          for (var i in data) {
            this.equipmentArr.push({
              equipmentName: data[i],
              equipmentCode: i,
            });
          }
        }
      });
    },
    // 选中设备,查询设备数据项
    equipChange(e) {
      console.log(e);
      equipConfigDataItemApi.queryByEquip(e).then((res) => {
        console.log(res);
        if (res.code === 1) {
          this.dataItemList = res.data || [];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 选择数据项
    chandataitem(i) {
      console.log(i);
      this.formData["dataItemName"] = this.dataItemList[i].dataItemName;
      this.formData["dataItemId"] = this.dataItemList[i].dataItemId;
      this.formData["dataTypeName"] = this.dataItemList[i].dataTypeName;
      this.formData["dataTypeId"] = this.dataItemList[i].dataTypeId;
    },
    // 添加一条上限数据
    addtopList() {
      let addvalue = {
        alarmLimitName: "",
        alarmLimitType: 0,
        alarmLimitValue: "",
      };
      this.nowtopList.push(addvalue);
    },
    // 删除一条上限数据
    deltopList(i) {
      this.nowtopList.splice(i, 1);
    },
    // 添加一条下限数据
    addbottomList() {
      let addvalue = {
        alarmLimitName: "",
        alarmLimitType: 1,
        alarmLimitValue: "",
      };
      this.nowbottomList.push(addvalue);
    },
    // 删除一条下限数据
    delbottomList(i) {
      this.nowbottomList.splice(i, 1);
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          let alarmLimitList = [];
          // this.basetopList.forEach(a => {
          //   if (a.alarmLimitName) {
          //     alarmLimitList.push(a)
          //   }
          // })
          // this.basebottomList.forEach(b => {
          //   if (b.alarmLimitName) {
          //     alarmLimitList.push(b)
          //   }
          // })
          this.formData.organizationMark = sessionStorage.organizationNo;
          if (this.formData.filteringValue) {
            this.formData.filteringValue = Number(this.formData.filteringValue);
          }
          if (this.nowChanceStau === "edit") {
            let editparams = {
              ...this.formData,
              alarmLimitList: alarmLimitList,
            };
            // 编辑接口
            basicAlarmConfigurationApi.editlist(editparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.nowChanceStau === "add") {
            // let addparams = {
            //   ...this.formData,
            //   alarmLimitList: alarmLimitList
            // }
            let addparams = {
              baseAlarmThresholdList: [
                // 上限数据
                this.basetopList,
                ...this.nowtopList,
                // 下限数据
                this.basebottomList,
                ...this.nowbottomList,
              ],
              alarmCharge: "", // 告警联系人名字
              ...this.formData,
            };
            console.log(addparams, this.basetopList,
            this.nowtopList,
                // 下限数据
                this.basebottomList,
                this.nowbottomList);
            return
            basicAlarmConfigurationApi.addlist(addparams).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.clearValidate();
      this.$emit("closeDialog");
      this.nowdataitemindex = "";
    },
    cancel() {
      this.clearValidate();
      this.$emit("cancelDialog");
    },

    clearValidate() {
      this.formData = {};
      this.$refs.ruleForm.clearValidate();
      this.$refs["ruleForm"].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.line-hang {
  width: 100%;
  display: flex;
}
.line-hang-con {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.line {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
}
.line-click {
  min-width: 30px;
  height: 30px;
  // background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  border: snow 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 5px;
  color: #fff;
  background-color: #003947;
  cursor: pointer;
}
</style>
